<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title">{{ title }}</span>
        <el-button style="float: right" size="mini" type="primary" @click="() => handleSave()">保存</el-button>
      </div>
      <div class="text item">
        <el-tabs v-model="activeName" :before-leave="handleBeforeLeaveTab">
          <el-tab-pane label="基本" name="basic">
            <el-form :model="product" :rules="rules" ref="productForm" label-width="100px" label-position="left">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="编号" prop="code">
                    <el-input v-model="product.code" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="product.name" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="规格型号" prop="model">
                    <el-input v-model="product.model" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="类型" prop="type">
                <el-radio-group v-model="product.type">
                  <el-radio :label="1">{{
                    $enums.productType.stock.text
                  }}</el-radio>
                  <el-radio :label="2">{{
                    $enums.productType.service.text
                  }}</el-radio>
                  <el-radio :label="3">{{
                    $enums.productType.asset.text
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="条码" prop="barCode">
                    <el-input v-model="product.barCode" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="计价单位" prop="basicUnitId">
                    <unit-select v-model="product.basicUnitId" style="width: 180px"></unit-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="默认税率" prop="defaultTaxRateId">
                    <taxrate-select v-model="product.defaultTaxRateId" style="width: 180px"></taxrate-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="控制">
                    <el-checkbox v-model="product.saleable">可销售</el-checkbox>
                    <el-checkbox v-model="product.purchasable">可采购</el-checkbox>
                    <el-checkbox v-model="product.producible">可生产</el-checkbox>
                    <el-checkbox v-model="product.outsourceable">可委外</el-checkbox>
                    <el-checkbox v-model="product.assetable">可资产</el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="库存" name="inventory">
            <el-form :model="productInventory" :rules="inventoryRules" ref="productInventoryForm" label-width="100px"
              label-position="left">
              <el-form-item label="计价方式" prop="pricingType">
                <el-select v-model="productInventory.pricingType" style="width: 180px">
                  <el-option label="移动平均" :value="2"> </el-option>
                  <el-option label="加权平均" :value="3"></el-option>
                  <el-option label="先入先出" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="仓库" prop="defaultWarehouseId">
                    <warehouse-select v-model="productInventory.defaultWarehouseId"
                      style="width: 180px"></warehouse-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="库位" prop="defaultLocationId">
                    <location-select v-model="productInventory.defaultLocationId"
                      :warehouseId.sync="productInventory.defaultWarehouseId" style="width: 180px"></location-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="启用批号" prop="enableBatchNumber">
                    <el-checkbox v-model="productInventory.enableBatchNumber"></el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="启用序列号" prop="enableSerialNumber">
                    <el-checkbox v-model="productInventory.enableSerialNumber"></el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="启用保质期" prop="enableShelfLife">
                    <el-checkbox v-model="productInventory.enableShelfLife"></el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="保质期（天）" prop="shelfLifeDays">
                    <el-input-number v-model="productInventory.shelfLifeDays" style="width: 180px"
                      controls-position="right" :min="0"
                      :disabled="!productInventory.enableShelfLife"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="最小库存" prop="minStockQuantity">
                    <el-input-number v-model="productInventory.minStockQuantity" style="width: 180px"
                      controls-position="right" :min="0"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="最大库存" prop="maxStockQuantity">
                    <el-input-number v-model="productInventory.maxStockQuantity" style="width: 180px"
                      controls-position="right" :min="0"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="安全库存" prop="safetyStockQuantity">
                    <el-input-number v-model="productInventory.safetyStockQuantity" style="width: 180px"
                      controls-position="right" :min="0"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="再订货点" prop="reorderPointQuantity">
                    <el-input-number v-model="productInventory.reorderPointQuantity" style="width: 180px"
                      controls-position="right" :min="0"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="采购" name="purchase">
            <el-form :model="productPurchase" :rules="purchaseRules" ref="productPurchaseForm" label-width="100px"
              label-position="left">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="采购单位" prop="purchaseUnitId">
                    <unit-select v-model="productPurchase.purchaseUnitId" style="width: 180px"></unit-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="默认供应商" prop="defaultSupplierId">
                    <supplier-select v-model="productPurchase.defaultSupplierId" style="width: 180px"></supplier-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="默认采购员" prop="defaultPurchaserId">
                    <employee-select v-model="productPurchase.defaultPurchaserId"
                      style="width: 180px"></employee-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="最小订单数" prop="minPurchaseQuantity">
                    <el-input-number v-model="productPurchase.minPurchaseQuantity" controls-position="right" :min="0"
                      style="width: 180px"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="销售" name="sale">
            <!-- <el-form :model="productInventory" :rules="rules"
              ref="productInventoryForm" label-width="100px" label-position="left">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="销售单位" prop="warehouseId">
                    <unit-select v-model="productInventory.warehouseId" style="width: 180px"></unit-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="最大订单数" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="最小订单数" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form> -->
          </el-tab-pane>
          <el-tab-pane label="生产" name="production">
            <!-- <el-form :model="productInventory" :rules="rules" ref="productInventoryForm" label-width="100px"
              label-position="left">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="生产单位" prop="warehouseId">
                    <unit-select v-model="productInventory.warehouseId" style="width: 180px"></unit-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="生产车间" prop="warehouseId">
                    <location-select v-model="productInventory.locationId"
                      :warehouseId.sync="productInventory.warehouseId" style="width: 180px"></location-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="领料仓库" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="领料库位" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="发料方式" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="超发控制" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="入库超收比例" prop="locationId">
                    <el-input v-model="product.saleable" style="width: 180px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form> -->
          </el-tab-pane>
          <el-tab-pane label="辅助单位" name="auxiliaryUnit"></el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>
<script>
import {
  getProduct, addProduct, updateProduct,
  getProductPurchase, addProductPurchase, updateProductPurchase,
  getProductInventory, addProductInventory, updateProductInventory
} from "@/api/product";
import unitSelect from "@/components/Select/unitSelect.vue"
import taxrateSelect from "@/components/Select/taxrateSelect.vue";
import warehouseSelect from "@/components/Select/warehouseSelect.vue";
import locationSelect from "@/components/Select/locationSelect.vue";
import supplierSelect from "@/components/Select/supplierSelect.vue";
import employeeSelect from "@/components/Select/employeeSelect.vue";
export default {
  components: {
    unitSelect,
    taxrateSelect,
    warehouseSelect,
    locationSelect,
    supplierSelect,
    employeeSelect
  },
  data() {
    return {
      product: {
        id: null,
        code: null,
        name: null,
        type: 1,
        model: null,
        basicUnitId: null,
        model: null,
        activated: true,
        barCode: null,
        saleable: false,
        purchasable: false,
        producible: false,
        outsourceable: false,
        assetable: false,
        defaultTaxRateId: null
      },
      rules: {
        code: [{ required: true, message: "请填写编号", trigger: "blur" }],
        name: [{ required: true, message: "请填写名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择产品类型", trigger: "blur" }],
        basicUnitId: [{ required: true, message: "请选择计量单位", trigger: "blur" }],
      },
      productInventory: {
        id: null,
        productId: this.id,
        pricingType: null,
        defaultWarehouseId: null,
        defaultLocationId: null,
        enableBatchNumber: false,
        enableShelfLife: false,
        shelfLifeDays: null,
        enableSerialNumber: false,
        minStockQuantity: null,
        maxStockQuantity: null,
        safetyStockQuantity: null,
        reorderPointQuantity: null,
      },
      inventoryRules: {
        pricingType: [{ required: true, message: "请选择计价类型", trigger: "blur" }],
        defaultWarehouseId: [{ required: true, message: "请选择仓库", trigger: "blur" }],
      },
      productPurchase: {
        id: null,
        productId: this.id,
        purchaseUnitId: null,
        defaultSupplierId: null,
        defaultPurchaserId: null,
        minPurchaseQuantity: null,
      },
      purchaseRules: {
        purchaseUnitId: [{ required: true, message: "请选择采购单位类型", trigger: "blur" }],
        defaultSupplierId: [{ required: true, message: "请选择默认供应商", trigger: "blur" }],
        defaultPurchaserId: [{ required: true, message: "请选择默认采购员", trigger: "blur" }],
      },
      title: "",
      activeName: null,
      productSaved: true,
      proudctPurchaseSaved: true
    };
  },
  methods: {
    getData() {
      if (!this.id) return;
      if (this.activeName == "basic") {
        getProduct(this.id).then((res) => {
          this.product = res || {};
        });
      } else if (this.activeName == "purchase") {
        getProductPurchase(this.id).then((res) => {
          this.productPurchase = res || { productId: this.id };
        });
      } else if (this.activeName == "inventory") {
        getProductInventory(this.id).then((res) => {
          this.productInventory = res || { productId: this.id };
        });
      }

    },
    handleSave() {
      if (this.activeName == "basic") {
        this.saveBasicData();
      } else if (this.activeName == "purchase") {
        this.savePurchaseData();
      } else if (this.activeName == "inventory") {
        this.saveInventoryData();
      }
    },
    saveBasicData() {
      this.$refs.productForm.validate((valid) => {
        if (valid) {
          if (!this.id) {
            addProduct(this.product).then((res) => {
              if (!res) return;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                position: "bottom-right",
              });
              this.productPurchase.productId = res.id;
              this.productInventory.productId = res.id;
              this.$emit("refresh", res);
            });
          } else {
            updateProduct(this.product).then((res) => {
              if (!res) return;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                position: "bottom-right",
              });
              this.$emit("refresh", res);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    savePurchaseData() {
      this.$refs.productPurchaseForm.validate((valid) => {
        if (valid) {
          if (!this.productPurchase.id) {
            addProductPurchase(this.productPurchase).then((res) => {
              if (!res) return;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                position: "bottom-right",
              });
              this.productPurchase = res;
              this.$emit("refresh", res);
            });
          } else {
            updateProductPurchase(this.productPurchase).then((res) => {
              if (!res) return;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                position: "bottom-right",
              });
              this.productPurchase = res;
              this.$emit("refresh", res);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveInventoryData() {
      this.$refs.productInventoryForm.validate((valid) => {
        if (valid) {
          if (!this.productInventory.id) {
            addProductInventory(this.productInventory).then((res) => {
              if (!res) return;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                position: "bottom-right",
              });
              this.productInventory = res;
              this.$emit("refresh", res);
            });
          } else {
            updateProductInventory(this.productInventory).then((res) => {
              if (!res) return;
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                position: "bottom-right",
              });
              this.productInventory = res;
              this.$emit("refresh", res);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleBeforeLeaveTab(newValue, oldValue) {
      // let tabSaved = true;
      // if (oldValue == "basic") {
      //   tabSaved = this.productSaved
      // } else if (oldValue == "purchase") {
      //   tabSaved = this.proudctPurchaseSaved
      // }
      // if (tabSaved)
      //   return;

      // this.$confirm('当前内容未保存,是否离开?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.productSaved = true;
      //   this.proudctPurchaseSaved = true;
      // }).catch(() => {
      //   this.activeName = oldValue;
      // });

    }
  },
  watch: {
    product: {
      handler(newValue, oldValue) {
        if (oldValue == undefined)
          return;
        if (JSON.stringify(newValue) != JSON.stringify(oldValue))
          this.productSaved = false;
      },
      immediate: true
    },
    productPurchase: {
      handler(newValue, oldValue) {
        if (oldValue == undefined)
          return;
        if (JSON.stringify(newValue) != JSON.stringify(oldValue))
          this.proudctPurchaseSaved = false;
      },
      immediate: true
    },
    activeName: {
      handler(val) {
        this.getData();
      },
      immediate: true
    }
  },
  mounted() {
    this.title = this.id ? "编辑" : "新增";
    this.activeName = "basic";
    //this.getData();
  },
  props: {
    id: {
      type: String,
      default: "",
    },
  },
};
</script>
<style scoped></style>
